import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class ClientManager {
    private static Map<String, Socket> clientList = new HashMap<>();
    private static ServerThread serverThread = null;
    private static InputStream inputStream;

    public static class ServerThread implements Runnable {

        private int port = 12345; //端口号
        private boolean isExit = false;//判断
        private ServerSocket serverSocket;

        public ServerThread() {

            try {
                serverSocket = new ServerSocket(port);
                System.out.println("端口：" + port + "服务开启成功");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("端口：" + port + "服务开启失败");
                System.out.println("失败原因：" + e.getMessage());
            }
        }


        @Override
        public void run() {
            while (!isExit) {
                System.out.println("等待连接...");
                try {
                    //获取手机address
                    final Socket socket = serverSocket.accept();
                    final String address = socket.getRemoteSocketAddress().toString();

//                    if(socket.getInputStream().read()){}


                    System.out.println("连接成功，手机地址为：" + address.toString());
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            synchronized (this) {
                                clientList.put(address, socket);
                            }
                            try {
                                inputStream = socket.getInputStream();
                                byte[] buffer = new byte[1024];
                                int lenth;
                                while ((lenth = inputStream.read(buffer)) != -1) {
                                    String text = new String(buffer, 0, lenth);
                                    System.out.println("接收到的数据为" + text.toString());
                                    sendAllMsg(text);
                                }


                            } catch (Exception e) {
                                e.printStackTrace();
                                System.out.println("连接失败，错误原因：" + e.getMessage());
                            } finally {
                                synchronized (this) {
                                    System.out.println("关闭" + address + "的连接");
                                    clientList.remove(address);
                                }
                            }

                        }
                    }).start();


                } catch (IOException e) {
                    e.printStackTrace();

                }


            }


        }

        public void Stop() {
            isExit = true;
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                    System.out.println("服务已关闭");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    public static ServerThread startServer(){
        System.out.println("开启服务");
        if (serverThread != null){
            showDown();
        }
        serverThread = new ServerThread();
        new Thread(serverThread).start();
        System.out.println("开启服务成功");
        return serverThread;
    }

    // 关闭所有server socket 和 清空Map
    public static void showDown(){
        for (Socket socket : clientList.values()) {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        serverThread.Stop();
        clientList.clear();
    }



        //全发
    public static boolean sendAllMsg(String msg) {


        try {
            for (Socket socket : clientList.values()) {
                OutputStream outputStream = socket.getOutputStream();
                outputStream.write(msg.getBytes("utf-8"));
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }


        return false;
    }
}
